import { Form, Input, message, Modal } from 'antd';
import { FormInstance } from 'antd/lib/form';
import FormItem from 'antd/lib/form/FormItem';
import React from 'react';
import { addOrganization, modifyOrganization } from '../../../../servers/servers';

interface OrganizationOperationProp {
  callback: () => any;
}

interface OrganizationOperationState extends OrganizationOperationProp {
  mode: 'create' | 'modify';
  visible: boolean;
  key: number;
}

/**
 * 职责： 新建或者编辑组织结构信息
 */
export class OrganizationOperation extends React.Component<
  OrganizationOperationProp,
  OrganizationOperationState
> {
  private formRef: React.RefObject<FormInstance>;

  constructor(prop: OrganizationOperationProp) {
    super(prop);
    this.formRef = React.createRef();
    this.state = {
      ...prop,
      mode: 'create',
      visible: false,
      key: 0,
    };
  }

  public open(
    mode: 'create' | 'modify',
    data?: { organizationName?: string; organizationId: number }
  ): void {
    this.setState({
      mode: mode,
      visible: true,
      key: data?.organizationId as number,
    });
    if (data) {
      setTimeout(() => {
        this.formRef.current?.setFieldsValue(data);
      }, 0);
    }
  }

  public close(): void {
    this.setState({
      visible: false,
    });
    const form = this.formRef.current;
    form?.resetFields();
    form?.setFieldsValue({});
  }

  private submitData(): void {
    const apiMap = {
      create: addOrganization,
      modify: modifyOrganization,
    };
    const mode = this.state.mode;
    const api = apiMap[mode] as any;
    const form = this.formRef.current;
    form
      ?.validateFields()
      .then(res => {
        const name = form.getFieldValue('organizationName');
        if (res) {
          api(this.state.key, name).then((res: any) => {
            message.success(`${mode === 'create' ? '新建' : '编辑'}成功`);
            this.state.callback();
            this.close();
          });
        }
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  render() {
    const { visible, mode } = this.state;

    return (
      <>
        <Modal
          title={mode === 'create' ? '新建组织' : '编辑组织'}
          onCancel={() => {
            this.close();
          }}
          onOk={() => {
            this.submitData();
          }}
          visible={visible}
        >
          <Form layout="horizontal" ref={this.formRef}>
            <FormItem
              label="组织名称"
              name="organizationName"
              rules={[{ required: true, message: '请输入15位内字符' }]}
              getValueFromEvent={event => {
                return event.target.value.replace(/\s+/g, '');
              }}
            >
              <Input maxLength={15} placeholder="请输入15位内字符" />
            </FormItem>
          </Form>
        </Modal>
      </>
    );
  }
}
